﻿module Sustainalytics.Common {

    export class NumberUtilityService {

        constructor(
            private $q: ng.IQService) {

            var ctx = this;
        }

        public getOrdinalName(cardinal: number, useCapital: boolean = false) {
            var ordinals =
                [
                    'zeroth',
                    'first',
                    'second',
                    'third',
                    'fourth',
                    'fifth',
                    'sixth',
                    'seventh',
                    'eighth',
                    'ninth',
                    'tenth',
                    'eleventh',
                    'twelfth',
                    'thirteenth',
                    'fourteenth',
                    'fifteenth',
                    'sixteenth',
                    'seventeenth',
                    'eighteenth',
                    'nineteenth',
                    'twentieth'
                ];

            var tens = {
                20: 'twenty',
                30: 'thirty',
                40: 'forty',
                50: 'fifty',
                60: 'sixty',
                70: 'seventy',
                80: 'eighty',
                90: 'ninety'
            };

            var ordinalTens = {
                30: 'thirtieth',
                40: 'fortieth',
                50: 'fiftieth',
                60: 'sixtieth',
                70: 'seventieth',
                80: 'eightieth',
                90: 'ninetieth',
                100: 'one hundredth',
                1000: 'one thousandth',
                1000000: 'one millionth'
            };


            var str = '';

            if (cardinal <= 20) {
                str = ordinals[cardinal];
            }
            else {
                if (cardinal % 10 === 0) {
                    str = ordinalTens[cardinal];
                }
                else {
                    str = tens[cardinal - (cardinal % 10)] + ordinals[cardinal % 10];
                }
            }

            if (useCapital) {
                str = str[0].toUpperCase() + str.substr(1, str.length - 1);
            }

            return str;
        }

        public getOrdinalNameEnd(cardinal: number): string {
            var ctx = this;
            var ordinal = ctx.getOrdinalName(cardinal, false);

            if (!ordinal)
                return null;

            var ordinalEnd = ordinal.substr(ordinal.length - 2, 2);
            return ordinalEnd;
        }
    }


    var mod = angular.module(commonModuleName);

    mod.factory('NumberUtilityService', function ($q) {
        return new NumberUtilityService($q);
    });
}